/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
limitations under the License.*/

package com.demo.ohos_zblibrary.manager;

import com.alibaba.fastjson.JSON;
import com.demo.ohos_zblibrary.application.DemoApplication;
import com.demo.ohos_zblibrary.model.User;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import zuo.biao.library.util.StringUtil;

import java.util.Optional;

/**数据工具类
 * @author Lemon
 */
public class DataManager {
    private final String TAG = "DataManager";

    private Context context;
    private DatabaseHelper databaseHelper;

    private DataManager(Context context) {
        this.context = context;
        databaseHelper = new DatabaseHelper(context);
    }

    private static DataManager instance;

    public static DataManager getInstance() {
        if (instance == null) {
            synchronized (DataManager.class) {
                if (instance == null) {
                    instance = new DataManager(DemoApplication.getInstance());
                }
            }
        }
        return instance;
    }

    // 用户 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private String PATH_USER = "PATH_USER";

    /**
     * key
     */
    public final String KEY_USER = "KEY_USER";

    /**
     * key id
     */
    public final String KEY_USER_ID = "KEY_USER_ID";

    /**
     * key name
     */
    public final String KEY_USER_NAME = "KEY_USER_NAME";

    /**
     * key phone
     */
    public final String KEY_USER_PHONE = "KEY_USER_PHONE";

    /**
     * key user id
     */
    public final String KEY_CURRENT_USER_ID = "KEY_CURRENT_USER_ID";

    /**
     * key last user id
     */
    public final String KEY_LAST_USER_ID = "KEY_LAST_USER_ID";

    /**
     * 判断是否为当前用户
     * @param userId u
     * @return boolean
     */
    public boolean isCurrentUser(long userId) {
        return userId > 0 && userId == getCurrentUserId();
    }

    /**
     * 获取当前用户id
     * @return long
     */
    public long getCurrentUserId() {
        User user = getCurrentUser();
        return user == null ? 0 : user.getId();
    }

    /**
     * 获取当前用户的手机号
     * @return String
     */
    public String getCurrentUserPhone() {
        User user = getCurrentUser();
        return user == null ? "" : user.getPhone();
    }

    /**
     * 获取当前用户
     * @return User
     */
    public User getCurrentUser() {
        Preferences preferences = databaseHelper.getPreferences(PATH_USER);
        return preferences == null ? Optional.ofNullable(getUser(preferences.getLong(
                KEY_CURRENT_USER_ID, 0))).get(): getUser(preferences.getLong(KEY_CURRENT_USER_ID, 0));
    }

    /**
     * 获取最后一次登录的用户的手机号
     * @return String
     */
    public String getLastUserPhone() {
        User user = getLastUser();
        return user == null ? "" : user.getPhone();
    }

    /**
     * 获取最后一次登录的用户
     * @return User
     */
    public User getLastUser() {
        Preferences preferences = databaseHelper.getPreferences(PATH_USER);
        return preferences == null ? Optional.ofNullable(getUser(preferences.getLong(KEY_LAST_USER_ID, 0)))
                .get() : getUser(preferences.getLong(KEY_LAST_USER_ID, 0));
    }

    /**
     * 获取用户
     * @param userId id
     * @return User
     */
    public User getUser(long userId) {
        Preferences preferences = databaseHelper.getPreferences(PATH_USER);
        if (preferences == null) {
            return Optional.ofNullable(JSON.parseObject(preferences
                    .getString(StringUtil.getTrimedString(userId), null), User.class)).get();
        }
        return JSON.parseObject(preferences.getString(StringUtil.getTrimedString(userId), null), User.class);
    }

    /**
     * 保存当前用户,只在登录或注销时调用
     * @param user  user == null >> user = new User();
     */
    public void saveCurrentUser(User user) {
        Preferences preferences = databaseHelper.getPreferences(PATH_USER);
        if (preferences == null) {
            return;
        }
        if (user == null) {
            user = new User();
        }

        preferences.delete(KEY_LAST_USER_ID).putLong(KEY_LAST_USER_ID, getCurrentUserId());
        preferences.delete(KEY_CURRENT_USER_ID).putLong(KEY_CURRENT_USER_ID, user.getId());
        preferences.flushSync();

        saveUser(preferences, user);
    }

    /**
     * 保存用户
     * @param user v
     */
    public void saveUser(User user) {
        saveUser(databaseHelper.getPreferences(PATH_USER), user);
    }

    /**
     * 保存用户
     * @param sdf sdf
     * @param user user
     */
    public void saveUser(Preferences sdf, User user) {
        if (sdf == null || user == null) {
            return;
        }
        String key = StringUtil.getTrimedString(user.getId());
        sdf.delete(key).putString(key, JSON.toJSONString(user)).flushSync();
    }

    /**
     * 删除用户
     * @param sdf pr
     * @param userId userid
     */
    public void removeUser(Preferences sdf, long userId) {
        if (sdf == null) {
            return;
        }
        sdf.delete(StringUtil.getTrimedString(userId)).flushSync();
    }

    /**
     * 设置当前用户手机号
     * @param phone phone
     */
    public void setCurrentUserPhone(String phone) {
        User user = getCurrentUser();
        if (user == null) {
            user = new User();
        }
        user.setPhone(phone);
        saveUser(user);
    }

    /**
     * 设置当前用户姓名
     * @param name name
     */
    public void setCurrentUserName(String name) {
        User user = getCurrentUser();
        if (user == null) {
            user = new User();
        }
        user.setName(name);
        saveUser(user);
    }

    // 用户 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}
